#!/usr/local/bin/python3
# -*- coding: utf-8 -*-
#
#  main.py
#
#  Copyright 2011 Arne Hüffmeier <ahueffme@gmail.com>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#
#


"""
automatic-rename

Usage:
automatic-rename.py [options] <path>

Options:
-h --help    Show this screen.
--version    Show version.
-n --ncurse    Use ncurse framwork.
-i --idOnly    Set Only ID.
"""


def __compare(path, season, serienID):
	fileList = flm.getFileList(path + "/" + season)
	compareList = []
	if season.endswith("eng"):
		httpList = http.getStaffeln(serienID, "en")
	else:
		httpList = http.getStaffeln(serienID, "de")
	for sfile in fileList:
		clean = sfile[1].replace("x264", "")
		clean = clean.replace("480p", "")
		clean = clean.replace("H.264", "")
		clean = clean.replace("720p", "")
		epi = re.findall(r"S[0-9]*E[0-9]*", clean, re.IGNORECASE)
		if len(epi) is 0:
			pass
		else:
			for e in epi:
				temp = e.lower()
				seasonNumber = temp[1:temp.find("e")]
				epiNumber = temp[temp.find("e") + 1:]
				try:
					int(seasonNumber)
					int(epiNumber)
				except ValueError:
					pass
				else:
					break
			try:
				compareList.append(((season + "/" + sfile[1]),
				httpList[int(seasonNumber)][int(epiNumber) - 1]))
			except ValueError:
				pass

	return compareList


def __cleanList(compareList):
	clean = []
	for i in compareList:
		if i[0].find(i[1].filename()) == -1:
			clean.append(i)
	return clean

#TODO: Auflisten von Dateien die nicht zugewordnet werden konnten


def __mainLoop(arguments, gui):
	dlist = flm.getDirList(arguments["<path>"])
	print("Es werden", len(dlist), "überprüft")
	for i in dlist:
		serienID = flm.getSerienID(arguments["<path>"] + i)
		if serienID is None:
			temp = http.getSerie(i, "de")
			serienID = gui.choseSerie(temp)
			if serienID is not None:
				flm.setSerienID(arguments["<path>"] + i, serienID)
		if arguments["--idOnly"] is not True and serienID is not None:
			dList = flm.getDirList(arguments["<path>"] + i)
			for season in dList:
				if season.startswith("S"):
					compareList = __compare((arguments["<path>"] + i), season, serienID)
					compareList = __cleanList(compareList)
					if len(compareList) != 0:
						changeList = gui.changeList(i, season, compareList)
						if changeList is not None:
							flm.setFiles(arguments["<path>"] + i, changeList)

import sys
import os
import re
import filemanager as flm
import httpConnection as http
from CliF import Cli


try:
	from docopt import docopt
except ImportError:
	print("please install docopt for python3.")
	sys.exit(-1)

if __name__ == "__main__":
	arguments = docopt(__doc__, version='automatic-rename 0.1')
	if not os.path.exists(arguments["<path>"]):
		print("Path not found")
		sys.exit(-1)
	if arguments["--ncurse"] is not True:
		gui = Cli()
	__mainLoop(arguments, gui)
